<template>
  <div class="event-list common-list-container__v2">
    <div ref="tableHeaderContainer" class="filter-wrapper">
      <form onsubmit="return false;">
        <div class="searh-input-box">
          <!-- 输入框搜索/重置 -->
          <div class="base-search-group input-with-append-search">
            <el-input
              v-model="searchParams.keywords"
              :placeholder="$t('im.list.pla1')"
              class="task-mr12 search-input"
            >
              <i slot="prefix" class="el-input__icon el-icon-search"></i>
              <el-button
                type="primary"
                slot="append"
                @click="
                  searchParams.pageNum = 1;
                  search();
                "
                native-type="submit"
                v-track="$track.formatParams('KEYWORD_SEARCH')"
              >
                {{$t('common.base.search')}}
              </el-button>
            </el-input>
            <el-button 
              type="ghost" 
              class="reset-btn" 
              @click="resetParams"
              v-track="$track.formatParams('RESET_SEARCH')"
            >{{$t('common.base.reset')}}</el-button
            >
          </div>
          <!-- 高级搜索 -->
          <div
            class="advanced-search-btn pointer"
            @click.self.stop="panelSearchAdvancedToggle"
          >
            <i class="iconfont icon-filter"></i>
            {{$t('common.base.advancedSearch')}}
          </div>
        </div>
      </form>
    </div>
    <div class="common-list-view__v2">
      <div ref="tableDoContainer" class="operate-box">
        <div class="operate-box__left">
          <!-- 删除 -->
          <!-- TODO CASE_DELETE editAll 权限 -->
          <!-- <el-button class="reset-btn delete-btn" @click="handleDelete">
            <i class="iconfont icon-delete task-icon task-font14"></i>
            删除
          </el-button> -->
        </div>
        <div class="operate-box__right">
          <!-- 更多操作 -->
          <!-- <el-dropdown v-if="isButtonDisplayed">
            <div class="cur-point">
              <span>更多操作</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
            <el-dropdown-menu slot="dropdown">
              
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="handleExport(false)">导出</div>
              </el-dropdown-item>
              <el-dropdown-item v-if="isButtonDisplayed">
                <div @click="handleExport(true)">导出全部</div>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->

          <!-- 选择列 -->
          <div class="guide-box">
            <div
              :class="['task-pointer', 'cur-point', 'ml_12']"
              @click="showAdvancedSetting"
              v-track="$track.formatParams('SELECT_COLUMN')"
            >
              <span>{{$t('common.base.choiceCol')}}</span>
              <i class="iconfont icon-fdn-select"></i>
            </div>
          </div>
        </div>
      </div>
      <div
        ref="BaseSelectionBarComponent"
        v-show="multipleSelection.length"
        class="common-list-selection__v2 mt_8"
      >
        <i18n path="common.base.table.selectedNth">
                  <span  place="count"
                  class="color-primary pad-l-5 pad-r-5"
          >{{ multipleSelection.length }}</span>
        </i18n>
        <span class="pointer" @click="toggleClearSelection">{{$t('common.base.clear')}}</span>
      </div>
      <!-- 表格 -->
      <el-table
        ref="table"
        class="mt_12 bbx-normal-list-box"
        stripe
        :row-key="getRowKey"
        :data="IMPage.list"
        :highlight-current-row="false"
        :border="true"
        @select="handleSelection"
        @select-all="handleSelection"
        @sort-change="sortChange"
        @header-dragend="headerDragend"
        v-loading="loading"
        header-row-class-name="common-list-table-header__v2"
        :height="tableContainerHeight"
      >
        <template slot="empty">
          <BaseListForNoData v-show="!loading" ></BaseListForNoData>
        </template>
        <!-- <el-table-column
          type="selection"
          width="48"
          align="center"
          class-name="select-column"
          :reserve-selection="true"
        ></el-table-column> -->
        <template v-for="column in columns">
          <el-table-column
            v-if="column && column.show"
            show-overflow-tooltip
            :align="column.align"
            :key="column.field"
            :label="column.displayName"
            :min-width="column.minWidth"
            :prop="column.field"
            :sortable="column.sortable"
            :width="column.width"
            :resizable="true"
            :fixed="column.fixLeft || false"
          >
            <template slot-scope="scope">
              <template v-if="column.renderCell">
                <base-table-cell
                  :render-cell="column.renderCell"
                  :column="column"
                  :row="scope.row"
                ></base-table-cell>
              </template>
              <template v-else-if="column.field ==='startTime_1'">
                {{formatDate(scope.row.startTime, 'YYYY-MM-DD HH:mm:ss')}}
              </template>
              <template v-else-if="column.isSystem === 1">
                {{
                  $formatFormField(column, scope.row)
                }}
              </template>
              <template v-else-if="column.field === 'relationUserId'">
                <template v-if="isOpenData">
                  <open-data type="userName" :openid="scope.row.relationUserStaffId"></open-data>
                </template>
                <template v-else>
                  {{scope.row[column.field]}}
                </template>
              </template>
              <template v-else-if="column.field ==='waitTime'">
                <TheTimer :time="scope.row.queueTime"></TheTimer>
              </template>
              <template v-else>
                {{
                  $formatFormField(column, scope.row)
                }}
              </template>
              
            </template>
          </el-table-column>
        </template>
        <el-table-column
          fixed="right"
          :label="$t('common.base.operation')">
          <template slot-scope="scope">
            <el-button 
              type="text"
              @click="accpetTask(scope.row)"
              v-track="$track.formatParams('QUEUE_SESSIONS_ALLOT')"
              >
              {{$t('common.task.button.allot')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息 -->
      <div ref="tableFooterContainer" class="table-footer bbx-normal-table-footer-12 pad-b-16 bg-w pad-t-16">
        <div class="list-info" >
          <i18n path="common.base.table.totalCount">
            <span place="count" class="level-padding">{{ IMPage.total || 0 }}</span>
          </i18n>
          <!-- 已选中
          <span
            class="color-primary pad-l-5 pad-r-5"
          >{{ multipleSelection.length }}</span>条
          <span class="color-primary cur-point" @click="toggleClearSelection">清空</span> -->
        </div>
        <el-pagination
          background
          hide-on-single-page
          :page-sizes="defaultTableData.defaultPageSizes"
          @current-change="jump"
          @size-change="handleSizeChange"
          :page-size="searchParams.pageSize"
          :current-page="searchParams.pageNum"
          layout="prev, pager, next, sizes, jumper"
          :total="IMPage.total"
        >
        </el-pagination>
      </div>

      <!-- 高级搜索框 -->
      <base-search-drawer
        :show.sync="visible"
        :storage-key="advancedColumnNumStorageKey"
        @reset="resetParams"
        @search="superSearch"
        @changeWidth="setAdvanceSearchColumn"
        @getColumnNum="setAdvanceSearchColumn"
      >
        <base-search-panel
          ref="searchPanel"
          :column-num="columnNum"
          :fields="advanceSearchColumn"
        />
      </base-search-drawer>

      <!-- 导出工单 -->
      <base-export-group
        ref="exportPanel"
        :alert="exportAlert"
        :columns="exportColumnList"
        :build-params="buildExportParams"
        :group="true"
        :validate="checkExportCount"
        method="post"
        :action="imListExport"
      />

      <!-- 选择列 -->
      <biz-select-column ref="advanced" @save="saveColumnStatus" />
    </div>
    <!-- 会话指派弹窗 -->
    <el-dialog
      :title="$t('im.lineup.title1')"
      :visible.sync="isForwarding"
      width="500px"
      style="background: transparent;"
      @close="closeDialog"
    >
      <!-- 内容主体区域 -->
      <el-form
        :model="ForwardingForm"
        :rules="ForwardingRules"
        ref="ForwardingRef"
        
        label-position="top"
      >
        <el-form-item prop="customerServiceId" :label="$t('im.lineup.title1')">
          <el-select
            style="width:100%"
            :placeholder="$t('common.placeholder.select')"
            clearable
            @change="ForwardingChange"
            v-model="ForwardingForm.customerServiceId"
          >
            <el-option
              v-for="item in AllCustomerList"
              :key="item.id"
              :value="item.id"
              :label="item.label"
            >
              <div class="option-item">
                <div class="info">
                  <span class="relationUserName">{{ item.customerServiceName }}</span>
                  <!-- 企业微信环境，使用open-data查询数据。其他环境正常显示 -->
                  <template v-if="isOpenData">
                    <span
                      style="margin-left: 10px"
                      v-if="item.relationUserStaffId"
                      >(<open-data
                        style="margin: 0"
                        type="userName"
                        :openid="item.relationUserStaffId"
                      ></open-data
                      >)</span
                    >
                  </template>
                  <template v-else>
                    <span
                      style="margin-left: 10px; max-width: 120px"
                      v-if="item.relationUserName"
                      class="relationUserName"
                      >({{ item.relationUserName }})</span
                    >
                  </template>
                </div>
                <div class="status">
                  <span
                    class="q"
                    :style="{ backgroundColor: item.color }"
                  ></span>
                  <span>{{ item.text }}</span>
                </div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('im.lineup.label1')" prop="forwardRemark">
          <el-input
            v-model="ForwardingForm.forwardRemark"
            :placeholder="$t('common.placeholder.inputSomething', {data1:''})"
            resize="none"
            type="textarea"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="ForwardingTitle"><span class="iconfont icon-fdn-info"></span>{{$t('im.lineup.tips1')}}</div>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isForwarding = false">{{$t('common.base.cancel')}}</el-button>
        <el-button type="primary" :loading="SaveForwardingLoading" @click="SaveForwarding">{{$t('common.base.confirm')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// pageDes 排队会话
import { isOpenData } from '@src/util/platform';
import { checkButtonDisplayed } from '@src/util/dom';

import * as IMApi from '@src/api/ImApi.js';
import * as _ from 'lodash';
import Page from '@model/Page';
import {
  getColumnFields,
  getAdvancedFields,
  getExportSystemInfo,
} from './fields';

import BaseSearchDrawer from 'packages/BaseSearchDrawer';
import BaseSearchPanel from 'packages/BaseSearchPanel';
import BaseTableCell from 'packages/BaseTableCell';
import TheTimer from './TheTimer.vue'

import { formatDate } from 'pub-bbx-utils';
import { storageGet, storageSet } from '@src/util/storage';

/* enum */
import StorageKeyEnum from '@model/enum/StorageKeyEnum.ts';
import { CustomerServiceWorkStatusMaps } from '@model/enum/ImEnum.js';

/* export & import */
import { imListExport } from '@src/api/Export';
import { safeNewDate } from '@src/util/time';
import { defaultTableData } from '@src/util/table'
// import { eventListImport_1, eventListImportTem_1 } from '@src/api/Import';

import AuthMixin from '@src/mixins/authMixin';


const IM_LIST_KEY = 'im_list_conversationList';
const IM_PAGE_SIZE_KEY = 'im_page_size_conversationList';

import i18n from '@src/locales'

export default {
  mixins: [AuthMixin],
  components: {
    [BaseSearchDrawer.name]: BaseSearchDrawer,
    [BaseSearchPanel.name]: BaseSearchPanel,
    [BaseTableCell.name]: BaseTableCell,
    TheTimer
  },
  data() {
    return {
      defaultTableData,
      isButtonDisplayed: checkButtonDisplayed(),
      isOpenData,
      searchParams: {
        keywords: '',
        pageSize: 10,
        pageNum: 1,
        orderDetail: {},
      },
      currentEventType: {},
      multipleSelection: [],

      IMPage: new Page(),
      visible: false,
      columns: [],
      columnNum: 1,
      exportColumnList: [],

      navWidth: window.innerWidth - 120,
      isFold: false,
      loading: true,
      hasSub: 1,
      advancedColumnNumStorageKey: StorageKeyEnum.IMListAdvancedColumnNum,
      searchParamsAll: {},
      AllPutChannel: [],
      AllServiceNumber:[],
      imListExport,
      ForwardingForm: {
        // 当前会话ID
        conversationId: '',
        // 会话转交备注
        forwardRemark: '',
        // 转交接收者的客服账号
        customerServiceId: '',
      },
      ForwardingRules:{
        customerServiceId:{
          required: true,
          message: i18n.t('im.lineup.tips2'),
          trigger: ['blur'],
        },
        forwardRemark:{ message: i18n.t('im.lineup.tips3'), max:200 }
      },
      isForwarding:false,
      AllCustomerList:[],
      SaveForwardingLoading:false,
      tableContainerHeight:'440px',
    };
  },
  computed: {
    // 高级搜索字段
    advanceSearchColumn() {
      return [...getAdvancedFields(this, this.AllPutChannel, this.AllServiceNumber)];
    },

    // 当前选中的工单ids
    selectedIds() {
      return this.multipleSelection.map((p) => p.id);
    },

    /** im列表字段 */
    imListFields() {
      const columnFields = getColumnFields(this);

      return []
        .concat(columnFields)
        .filter((f) => f.formType !== 'separator' && f.formType !== 'info')
        .sort((a, b) => a.orderId - b.orderId);
    },
    allowImView() {
      return this.globalIsHaveImViewDetailAuth
    }
  },
  created(){
    let that_ = this;
    window.addEventListener('message', (event)=>{
      const {action, data} = event.data;
      if(data?.notifyType == 'lineConversation'){
        this.search()
      }else if (action == 'shb.frame.activatedPage'){
        that_.$nextTick(()=> {
          that_.knowTableContainerHeight();
        })
      }
    }, false)
  },
  async mounted() {

    // 获取缓存的pagesize
    const localStorageData = await this.getLocalStorageData();
    this.searchParams.pageSize = localStorageData[IM_PAGE_SIZE_KEY] || 10;
    this.initialize(); // 获取初始化数据
    this.search();
    // this.getAllPutChannel();
    // this.getAllServiceNumber()
    // 获取客服列表
    this.getAllCustomerService()
    this.$nextTick(()=> {
      this.knowTableContainerHeight()
      let that_ = this;
      window.onresize = _.debounce(()=>{
        that_.knowTableContainerHeight();
        that_.navWidth = window.innerWidth - 120;
      }, 500)
    })
  },
  methods: {
    formatDate,
    // 获取渠道列表
    getAllPutChannel() {
      IMApi.getAllPutChannel().then((res) => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllPutChannel = data.map((item) => {
          item.text = item.channelName;
          item.value = item.id;
          return item;
        });
      });
    },
    // 获取客服编号
    getAllServiceNumber() {
      IMApi.getAllCustomerService().then((res) => {
        const { code, message = this.$t('common.base.tip.systemIsError'), data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllServiceNumber = data.map((item) => {
          item.text = item.customerServiceNumber;
          item.value = item.customerServiceNumber;
          return item;
        });
      });
    },
    // 获取服务会话列表
    queryConversationList(params = {}) {
      this.loading = true;
      IMApi.getLineConversationList(params)
        .then((res) => {
          if (res.code == 0) {
            this.IMPage = res.data || [];
          }
        })
        .catch((err) => {
          console.error(err);
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 搜索
    search() {
      // 获取高级搜索参数
      let advancedSearchParams = this.$refs.searchPanel
        ? this.$refs.searchPanel.buildParams()
        : {};
      const { customerId = '' } = advancedSearchParams;
      const searchParams = {
        ...this.searchParams,
        ...advancedSearchParams,
        customerId,
      };
      this.searchParamsAll = searchParams;
      this.visible = false;
      this.queryConversationList(searchParams);
    },

    // 重置
    resetParams() {
      const fromId = window.frameElement.getAttribute('id');
      this.$platform.refreshTab(fromId);
    },

    // 高级搜索
    panelSearchAdvancedToggle() {
      this.visible = true;
    },

    // 删除
    async handleDelete() {
      const { selectedIds } = this;
      if (!selectedIds.length) {
        this.$platform.alert(this.$t('im.list.tips1'));
        return;
      }

      this.$confirm(this.$t('im.list.tips2'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.confirm'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
        .then(async () => {
          const { code } = await IMApi.removeConversations(selectedIds);
          if (code == 0) {
            this.$platform.alert(this.$t('common.base.tip.deleteSuccess'));
            this.toggleClearSelection();
            this.search();
          }
        })
        .catch(() => {});
    },

    /**
     * @description: 导出（全部）
     * @param {Boolean} isExportAll 是否导出全部
     */
    async handleExport(isExportAll) {
      let ids = [];
      let fileName = `${formatDate(safeNewDate(), 'YYYY-MM-DD')}im列表数据.xlsx`;
      if (!isExportAll) {
        if (!this.multipleSelection.length)
          return this.$platform.alert(this.$t('common.base.tip.exportUnChooseTip'));
        ids = this.selectedIds;
      }

      const ExportPanelComponent = this.$refs.exportPanel;
      if (!ExportPanelComponent) {
        return console.warn('Caused: $refs.exportPanel is Empty');
      }

      const LocalStorageData = await this.getLocalStorageData();
      let exportCheckedData = LocalStorageData.exportCheckedData;

      if (!exportCheckedData) {
        exportCheckedData = {
          checkedGroup: [],
          checkedMap: {},
          isCheckedAll: false,
          tooltip: true,
        };
      }

      ExportPanelComponent.open(ids, fileName, false, exportCheckedData);
    },

    async initialize(isEventStatus) {
      // Todo接口调用更改
      // 清除导出配置的缓存
      localStorage.removeItem('checkedMap');
      localStorage.removeItem('checkedGroupArr');
      localStorage.removeItem('isCheckedAll');
      this.columns = this.imListFields;
      this.buildColumns(); // 构建表格/选择列字段
      this.buildExportColumns(); // 构建导出字段
    },

    // 构建列表项
    async buildColumns() {
      // 获取缓存在本地的选择列配置
      const localStorageData = await this.getLocalStorageData();
      const columnStatus = localStorageData.columnStatus || [];

      const localColumns = columnStatus
        .map((i) => (typeof i == 'string' ? { field: i, show: true } : i))
        .reduce((acc, col, currentIndex) => {
          acc[col.field] = {
            field: col,
            index: currentIndex,
          };
          return acc;
        }, {});

      let imListFields = this.imListFields; // 本地默认的表格项字段
      if (Array.isArray(columnStatus) && columnStatus.length > 0) {
        // 有本地缓存--列表排序
        imListFields = this.buildSortFields(imListFields, localColumns);
      }

      const columns = imListFields.map((col) => {
        // 选择列配置 是否勾选（显示）&宽度
        let show = col.show === true;
        let { width } = col;
        let localField = localColumns[col.field]?.field || null;
        let fixLeft = localField?.fixLeft || null;
        if (null != localField) {
          if (localField.width) {
            width = typeof localField.width == 'number'
              ? `${localField.width}px`
              : localField.width;
          }
          show = localField.show !== false;
        } else {
          show = true;
        }

        col.show = show;
        col.width = width;
        col.minWidth = col.width || 150;
        col.type = 'column';
        col['fixLeft'] = fixLeft && 'left'
        return col;
      });

      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
      });
    },

    // 选择列排序
    buildSortFields(originFields = [], fieldsMap = {}) {
      let fields = [];
      let unsortedFields = [];

      originFields.forEach((originField) => {
        let { fieldName } = originField;
        let field = fieldsMap[fieldName];

        if (field) {
          let { index } = field;
          fields[index] = originField;
        } else {
          unsortedFields.push(originField);
        }
      });

      return fields.concat(unsortedFields);
    },

    // 构建导出项
    buildExportColumns() {
      // im列表信息
      // 系统信息
      const systemInfo = {
        label: this.$t('common.form.fieldGroupName.system2'),
        value: 'systemChecked',
        columns: getExportSystemInfo().map((item) => {
          item.export = true;
          item.label = item.displayName;
          return item;
        }),
      };
      this.exportColumnList = [systemInfo].filter((item) => {
        return item.columns && item.columns.length > 0;
      });
    },

    // 打开选择列
    showAdvancedSetting() {
      this.$refs.advanced.open(this.columns, this.currentEventType);
    },

    /**
     * @description 表头更改
     */
    headerDragend(newWidth, oldWidth, column, event) {
      let data = this.columns
        .map((item) => {
          if (item.fieldName === column.property) {
            item.width = column.width;
          }
          return item;
        })
        .map((item) => {
          return {
            field: item.field,
            show: item.show,
            width: item.width,
          };
        });
      this.modifyColumnStatus({ type: 'column', data });
    },

    /**
     * @description 修改选择列设置
     * @param {Object} event 事件对象
     */
    modifyColumnStatus(event) {
      let columns = event.data || [],
        colMap = columns.reduce(
          (acc, col) => (acc[col.field] = col) && acc,
          {}
        );
      this.columns.forEach((col) => {
        let newCol = colMap[col.field];
        if (null != newCol) {
          this.$set(col, 'show', newCol.show);
          this.$set(col, 'width', newCol.width);
        }
      });

      this.saveColumnStatusToStorage();
    },

    // 保存选择列配置
    saveColumnStatus(event) {
      let columns = event.data || [];

      this.columns = [];
      this.$nextTick(() => {
        this.$set(this, 'columns', columns.slice());
        this.saveColumnStatusToStorage();
      });
      this.$message.success(this.$t('common.base.saveSuccess'));
    },

    // 保存选择列配置到本地
    saveColumnStatusToStorage() {
      const localStorageData = this.getLocalStorageData();
      let columnsStatus = null;

      // 判断是否存储选择列
      const columnsList = this.columns.map((c) => ({
        field: c.field,
        show: c.show,
        width: c.width,
        fixLeft:c.fixLeft
      }));

      if (localStorageData.columnStatus) {
        localStorageData.columnStatus = columnsList;
        columnsStatus = localStorageData.columnStatus;
      } else {
        columnsStatus = columnsList;
      }

      this.saveDataToStorage('columnStatus', columnsStatus);
    },

    /**
     * @description 获取行的key
     * @param {Object} row 行数据
     * @return {String} key
     */
    getRowKey(row = {}) {
      return row.id;
    },

    // 清空选择框
    toggleClearSelection() {
      this.multipleSelection = [];
      this.$refs.table.clearSelection();
    },

    // 表格选择操作
    handleSelection(selection) {
      this.multipleSelection = selection;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },

    // 排序变化
    sortChange(option) {
      const { column, order, prop } = option;
      const sortedField = this.columns.filter((item) => item.fieldName === prop)[0] || {};
      if (column === null) {
        this.searchParams.orderDetail = {};
      } else {
        this.searchParams.orderDetail = {
          column: sortedField.sortName,
          sequence: order === 'ascending' ? 'ASC' : 'DESC',
          type: sortedField.dataType,
          isSystem: sortedField.isSystem,
        };
      }
      this.search();
    },

    // 页码跳转
    jump(pageNum) {
      this.searchParams.pageNum = pageNum;
      this.IMPage.list = [];
      this.search();
    },

    // 页大小改变
    handleSizeChange(pageSize) {
      this.saveDataToStorage(IM_PAGE_SIZE_KEY, pageSize);
      this.searchParams.pageSize = pageSize;
      this.searchParams.pageNum = 1;
      this.search();
    },

    // 设置高级搜索展示列数
    setAdvanceSearchColumn(command) {
      this.columnNum = Number(command);
    },

    // 构建导出参数
    buildExportParams(checkedMap, ids) {
      const { systemChecked } = checkedMap;

      let exportAll = !ids || !ids.length;
      let exportTotal = exportAll ? this.IMPage.total : this.selectedIds.length;
      const exportSearchModel = {
        exportTotal,
        ...this.searchParamsAll,
      };

      let params = {
        dataTotal: exportTotal,
        exportSearchModel: JSON.stringify(exportSearchModel),
      };
      let export_sys = this.exportData('systemChecked', systemChecked);
      params['ids'] = exportAll ? '' : this.selectedIds.join(',');
      params['checked'] = export_sys
        .map((item) => {
          return item;
        })
        .join(',');

      return params;
    },

    /**
     * 导出数据
     */
    exportData(type, list = []) {
      const export_list = this.exportColumnList;
      let xlistColumns = [];
      export_list.forEach((xlist, i) => {
        if (xlist.value === type) xlistColumns = xlist.columns;
      });

      return xlistColumns
        .map((v) => {
          let bool = list.some((item) => {
            if (v.exportAlias) {
              return v.exportAlias === item;
            }
            return v.fieldName === item;
          });
          if (bool) {
            return v.exportAlias ? v.exportAlias : v.fieldName;
          }
        })
        .filter((item) => {
          return item;
        });
    },

    // 导出提示
    exportAlert(result, params = {}) {
      this.$platform.alert(result.message);
    },

    /**
     * @description 检测导出条数
     * @return {String | null}
     */
    checkExportCount(ids, max) {
      let exportAll = !ids || ids.length == 0;
      return exportAll && this.IMPage.total > max
        ? this.$t('common.base.tip.exportMostTip')
        : null;
    },

    // 获取本地localstorage
    getLocalStorageData() {
      const dataStr = storageGet(IM_LIST_KEY, '{}');
      return JSON.parse(dataStr);
    },

    // 保存数据到本地localstorage
    saveDataToStorage(key, value) {
      const data = this.getLocalStorageData();
      data[key] = value;
      storageSet(IM_LIST_KEY, JSON.stringify(data));
    },
    // 指派按钮
    accpetTask(obj){
      this.ForwardingForm.conversationId = obj.id
      this.isForwarding = true
    },
    // 高级搜索
    superSearch(){
      this.searchParams.pageNum = 1
      this.search()
    },
    // 获取会话转交数据
    getAllCustomerService(){
      IMApi.getAllCustomerService().then((res) => {
        const { code, message = '系统错误', data = [] } = res;
        if (code !== 0) return this.$platform.alert(message);
        this.AllCustomerList = data.map(v=>{
          return {
            ...v,
            label: v.customerServiceName,
            text: CustomerServiceWorkStatusMaps[v.status].text,
            color: CustomerServiceWorkStatusMaps[v.status].color,
          }
        });});
      // 去除当前客户
      // let UserID = this.imConversationInfo.relationUserId
      // this.AllCustomerList = this.AllCustomerList.filter(item=>UserID !== item.relationUserId)
    },
    // 选中的话转交数据
    ForwardingChange(id){
      const item = this.AllCustomerList.find(item=>item.id === id)
      this.ForwardingItem = item
      this.ForwardingForm.customerServiceId = item ? item.id : ''
    },
    SaveForwarding(){
      this.$refs.ForwardingRef.validate( async (valid)=>{
        if(!valid) return;
        try{
          this.SaveForwardingLoading = true
          const {code} = await IMApi.conversationTransfer(this.ForwardingForm)
          if(code == 0){
            this.$notify({
              title: this.$t('im.lineup.title1'),
              message: this.$t('im.lineup.tips4'),
              type: 'success'
            });
            this.superSearch()
            this.ForwardingForm.forwardRemark = ''
          }else{
            this.$notify({
              title: this.$t('im.lineup.title1'),
              message: this.$t('im.lineup.tips5'),
              type: 'error'
            });
          }
        }finally{
          this.isForwarding = false
          this.SaveForwardingLoading = false
        }
      })
    },
    /**
     * @des 获取列表当前的可滚动高度
     */
    knowTableContainerHeight(){
      let min = 440;
      try {
        let window_ = window.innerHeight;
        let header = this.$refs.tableHeaderContainer?.offsetHeight || 0;
        let do_ = this.$refs.tableDoContainer?.offsetHeight || 0;
        let footer = this.$refs.tableFooterContainer?.offsetHeight || 0;
        let selection = this.$refs.BaseSelectionBarComponent?.offsetHeight || 0;
        selection = selection ? selection + 8 : selection;
        min = window_ - header * 1 - do_ * 1 - footer * 1 - selection * 1 - 24 - 12 - 8 - 16;
        console.log(window_, header, do_, footer, selection, 'window_, header, do_, footer, selection');
        // console.log(pxArray, 'pxArray')
        min = min > 440 ? min : 440;
      } catch (error) {
        console.warn(error, 'error try catch');
      }
      this.$set(this, 'tableContainerHeight', `${min}px`)
    },
    changePackUp(){
      this.packUp = !this.packUp;
      this.$nextTick(()=>{
        this.knowTableContainerHeight()
      })
    },
    closeDialog(){
      this.$refs.ForwardingRef.resetFields();
    },
  },
};
</script>


<style lang="scss" scoped>
.event-list {
  .search-input {
    width: 440px;
  }

  > div {
    background: #fff;
    border-radius: 4px;
  }

  .filter-wrapper {
    margin-bottom: 12px;
    .searh-input-box {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid #f2f2f2;
      .advanced-search-btn {
        @include fontColor;
      }
      .base-search-group {
        margin-right: 24px;
      }
    }
    .filter-tab {
      &__item {
        display: flex;
        flex-wrap: wrap;
        line-height: 32px;
        border-bottom: 1px solid #f2f2f2;
        &:last-child {
          border-bottom: 0;
        }
      }
      &__label {
        background: #f5f5f5;
        width: 108px;
        text-align: center;
        color: #666;
      }
      &__content {
        position: relative;
        display: flex;
        flex-wrap: wrap;
        flex: 1;
        height: auto;
        .content-item {
          display: inline-block;
          width: 130px;
          overflow: hidden;
          padding-left: 10px;
          cursor: pointer;
          white-space: nowrap;
          text-overflow: ellipsis;
          color: grey;
          &:hover {
            color: #333;
          }
          .content-item-label.actived {
            color: $color-primary-light-6 !important;
          }
        }
        .fold-btn {
          position: absolute;
          right: 10px;
        }
      }
      &__content.fold {
        height: 30px;
        overflow: hidden;
      }
    }
  }

  .common-list-view__v2 {
    padding-bottom:0;
    .operate-box {
      .cur-point {
        color: #595959;
      }
      display: flex;
      justify-content: space-between;
      align-items: center;
      > div {
        display: flex;
        align-items: center;
        .icon-dingyuetongzhiguanli {
          font-size: 14px;
          &.actived {
            color: $color-primary-light-6;
          }
        }
      }
    }
  }
}
.reset-btn {
  background: #f5f8fa;
}
.delete-btn {
  padding-right: 16px !important;
}
.import-event {
  position: relative;
  left: -15px;
  padding-left: 15px;

  &:hover &-item {
    display: block;
  }

  &-item,
  .import-event-item-children {
    position: absolute;
    background: #fff;
    color: #333;
    left: -115px;
    top: -1px;
    border: 1px solid #eee;
    border-radius: 4px;
    display: none;

    > div {
      padding: 4px 15px;
      width: 120px;
      position: relative;

      &:hover {
        background-color: $color-primary-light-1;
        color: $color-primary-light-6;
      }
    }
  }

  &-item {
    top: -7px;
    > div:hover {
      .import-event-item-children {
        display: block;
      }
    }
  }
}
</style>
<style lang="scss">
.wx-im {
  color: $color-main;
  font-size: 10px;
}
.option-item {
  display: flex;
  width: 100%;
  justify-content: space-between;
  .info {
    display: flex;
    .relationUserName {
      max-width: 80px;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
  .status {
    display: flex;
    align-items: center;
    .q {
      width: 6px;
      height: 6px;
      background-color: red;
      margin-right: 6px;
      border-radius: 100%;
    }
  }
}
</style>